import chalk from "chalk";

const glob = require('glob'); //引入glob处理文件
const fs = require('fs');
const path = require('path');

// 路径分隔符
const pathSeparator = process.platform === 'darwin' ? '/' : '\\';

function getFiles(siteName) {
    const returnPath = siteName === false ? './src/pug/' : `./sites/${siteName}/pug/`
    return glob
        .sync(siteName === false ? './src/pug/*.pug' : `./sites/${siteName}/pug/*.pug`)
        .map(filepath => {
            const list = filepath.split(/[\/|\/\/|\\|\\\\]/g); // 斜杠分割文件目录
            const fullname = list[list.length - 1].replace(/\.js/g, '');
            // 拿到文件的 filename
            const name = fullname.substring(0, fullname.lastIndexOf('.'));
            return {
                path: returnPath +
                    pathSeparator +
                    name +
                    '.pug',
                filename: name
            };
        });
}

function getTpl(siteName) {
    const returnPath = siteName === false ? './src/pug/' : `./sites/${siteName}/pug/`
    const files = glob
        .sync(siteName === false ? './src/pug/*.pug' : `./sites/${siteName}/pug/*.pug`)
        .map(filepath => {
            const list = filepath.split(/[\/|\/\/|\\|\\\\]/g); // 斜杠分割文件目录
            const fullname = list[list.length - 1].replace(/\.js/g, '');
            // 拿到文件的 filename
            const name = fullname.substring(0, fullname.lastIndexOf('.'));
            return {
                path: returnPath +
                    pathSeparator +
                    name +
                    '.pug',
                filename: name
            };
        });
    let tpl = `<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    <body>
${files
            .map(f => {
                return `        <a href="${f.filename + '.html'}">${
                    f.filename
                    }</a><br>`;
            })
            .join('\n')}
    </body>
</html>`;
    const name = process.argv.slice(2)[0]; // 判断是否是新建
    if (name === 'dev' || name === 'd') {
        fs.writeFile('./src/webpackGuidance_tpl.html', tpl, function (err) {
            if (err) throw err;
        });

        files.push({
            path: './src/webpackGuidance_tpl.html',
            filename: 'webpackGuidance'
        });
    }

    return files;
}

let postcssConfig = {
    //关于postcss的配置
    loader: 'postcss-loader',
    options: {
        ident: 'postcss',
        plugins: () => [
            require('postcss-import')({
                //将所有样式合并在一起
                addDependencyTo: 'webpack'
            }),
            require('postcss-url')({
                url: 'rebase'
                // from: 'zunyi-xuezhan/css/style.css',
                // to: 'dist/main.css'
            }), //不知道如何重置路径
            // require('stylelint')({
            //     configFile: path.resolve(__dirname, 'stylelint.config.js')
            // }),
            require('postcss-reporter')({
                learMessages: true
            }),
            require('postcss-assets')({
                basePath: '/',
                loadPaths: ['images/'],
                relative: true
            }),
            // require('autoprefixer')({
            //   // browsers: ['last 5 versions']
            // }),
            require('postcss-cssnext')(), //postcss-cssnext内置了autoprefixer的功能
            // require('postcss-modules')({
            //     generateScopedName: '[name]__[local]___[hash:base64:5]'
            // }),
            require('precss'),
            require('cssnano')({
                preset: 'default'
            })
        ]
    }
}

let getUserConfig = () => {
    let fileConfig;
    const configPath = (
        path.resolve(process.cwd(), 'beon.config.js')
    )
    if (fs.existsSync(configPath)) {
        try {
            fileConfig = require(configPath)
            if (typeof fileConfig === 'function') {
                fileConfig = fileConfig()
            }

            if (!fileConfig || typeof fileConfig !== 'object') {
                error(
                    `Error loading ${chalk.bold('beon.config.js')}: should export an object or a function that returns object.`
                )
                fileConfig = null
            }
        } catch (e) {
            error(`Error loading ${chalk.bold('beon.config.js')}:`)
            throw e
        }
    }
    return fileConfig
}

module.exports = {
    getTpl,
    getFiles,
    postcssConfig,
    getUserConfig
};
